package com.andreamerla.petslife.fragment;

import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.andreamerla.petslife.R;
import com.andreamerla.petslife.activity.GpsActivity;
import com.andreamerla.petslife.activity.VetSearchActivity;
import com.andreamerla.petslife.adapter.PlaceAdapter;
import com.andreamerla.petslife.manager.AlertDialogManager;
import com.andreamerla.petslife.manager.GooglePlacesManager;
import com.andreamerla.petslife.model.Place;
import com.andreamerla.petslife.model.PlaceList;
import com.andreamerla.petslife.util.Response;
import com.andreamerla.petslife.util.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: a.merla
 * Date: 22/07/13
 * Time: 17.34
 */
public class VetSearchListFragment extends Fragment implements View.OnClickListener {
    private SeekBar sbRadius;
    private EditText etRadius;
    private ImageView ivSearch;
    private ListView lvResults;
    private List<Place> placeList = new ArrayList<Place>();

    private PlaceAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.vet_search_layout, null);

        sbRadius = (SeekBar) view.findViewById(R.id.sb_radius);
        sbRadius.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && etRadius != null)
                    etRadius.setText(Integer.toString(progress));
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
                // Do nothing
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
                // Do nothing
            }
        });
        etRadius = (EditText) view.findViewById(R.id.et_radius);
        etRadius.setText(Integer.toString(sbRadius.getProgress()));
        etRadius.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (sbRadius != null)
                    sbRadius.setProgress((int) Math.round(Double.parseDouble(etRadius.getText().toString())));
                return false; // Return true if you have consumed the action, else false
            }
        });
        ivSearch = (ImageView) view.findViewById(R.id.iv_search);
        ivSearch.setOnClickListener(this);

        lvResults = (ListView) view.findViewById(R.id.lv_results);
        adapter = new PlaceAdapter(getActivity(), placeList);
        lvResults.setAdapter(adapter);

        return view;
    }

    public void onClick(View view) {
        if (view == ivSearch) {
            Utils.hideKeyboard(getActivity(), view);
            new LoadPlacesTask().execute();
        }
    }

    public List<Place> getPlaceList() {
        return placeList;
    }

    private class LoadPlacesTask extends AsyncTask<Void, Void, Void> {
        PlaceList nearPlaces;

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                Location location = ((GpsActivity) getActivity()).gpsTracker.getLocation();
                int radius = (int) (Double.parseDouble(etRadius.getText().toString()) * 1000) + 1; // Added 1 meter to prevent INVALID_REQUEST for radius == 0
                String types = "veterinary_care";
                boolean rankByDistance = true;

                if (location != null)
                    nearPlaces = GooglePlacesManager.nearbySearch(location.getLatitude(), location.getLongitude(), radius, types, rankByDistance);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            placeList.clear();

            String status = nearPlaces != null ? nearPlaces.status : Response.ERROR.getName();

            if (status.equals(Response.OK.getName())) {
                if (nearPlaces.results != null)
                    placeList.addAll(nearPlaces.results);
            } else {
                Response response = Response.getResponseByName(status);
                if (response == null)
                    response = Response.ERROR;
                AlertDialogManager.showAlertDialog(getActivity(), response.getName(), response.getDescription());
            }

            adapter.notifyDataSetChanged();
        }
    }
}
